package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"good_srv/good"
	"good_srv/internal/svc"
	"good_srv/model/mysql"
	"good_srv/pkg"
	"strconv"
)

type OrderPayLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderPayLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderPayLogic {
	return &OrderPayLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderPayLogic) OrderPay(in *good.OrderPayRequest) (*good.OrderPayResponse, error) {
	// todo: add your logic here and delete this line
	var g mysql.Good
	err := g.FindGood(in.GoodId)
	if err != nil {
		return nil, fmt.Errorf("该商品不存在")
	}
	if g.Stock < in.Num {
		return nil, fmt.Errorf("库存不够")
	}
	total := g.Price * float64(in.Num)
	numbering := uuid.NewString()
	var order = mysql.Order{
		UserId:    in.UserId,
		Numbering: numbering,
		Title:     g.Title,
		Times:     in.Times,
		Status:    g.Status,
		Total:     total,
	}
	err = order.Order()
	if err != nil {
		return nil, fmt.Errorf("订单生成失败")
	}
	var orderGood = mysql.OrderAdd{
		GoodId:  in.GoodId,
		OrderId: int64(order.ID),
		Title:   g.Title,
		Status:  g.Status,
		Num:     in.Num,
		Price:   g.Price,
	}
	err = orderGood.OrderAdd()
	if err != nil {
		return nil, fmt.Errorf("订单生成失败")
	}
	pay := pkg.AliPay{
		Subject:     g.Title,
		OutTradeNo:  numbering,
		TotalAmount: strconv.Itoa(int(total)),
	}
	payUrl := pay.Pay()
	return &good.OrderPayResponse{
		OrderId: int64(order.ID),
		PayUrl:  payUrl,
	}, nil
}
